package com.example;

import javafx.fxml.FXML;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.converter.DoubleStringConverter;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import javafx.scene.control.Alert;

import java.sql.SQLException;
import java.util.List;

public class TeacherViewStudentGradesController implements TeacherSubController {

    @FXML
    private TableView<Grade> studentGradesTableView;
    @FXML
    private TableColumn<Grade, String> studentUsernameColumn;
    @FXML
    private TableColumn<Grade, String> studentNameColumn;
    @FXML
    private TableColumn<Grade, String> courseNameColumn;
    @FXML
    private TableColumn<Grade, String> semesterColumn;
    @FXML
    private TableColumn<Grade, Double> scoreColumn;

    @FXML
    private TextField studentUsernameField;
    @FXML
    private TextField studentNameField;
    @FXML
    private TextField courseNameField;
    @FXML
    private TextField semesterField;
    @FXML
    private Button searchButton;

    private Stage primaryStage;
    private TeacherController teacherController;
    private User currentUser;
    private GradeDAO gradeDAO;

    @Override
    public void setPrimaryStage(Stage primaryStage) {
        // This sub-controller doesn't need the primary stage directly
    }

    @Override
    public void setTeacherController(TeacherController teacherController) {
        this.teacherController = teacherController;
    }

    @Override
    public void setCurrentUser(User user) {
        this.currentUser = user;
        System.out.println("TeacherViewStudentGradesController: setCurrentUser called with user: " + (user != null ? user.getUsername() : "null"));
    }

    @FXML
    public void initialize() {
        gradeDAO = new GradeDAO();

        // Setup table columns
        studentUsernameColumn.setCellValueFactory(new PropertyValueFactory<>("studentUsername"));
        studentNameColumn.setCellValueFactory(new PropertyValueFactory<>("studentName"));
        courseNameColumn.setCellValueFactory(new PropertyValueFactory<>("courseName"));
        semesterColumn.setCellValueFactory(new PropertyValueFactory<>("semester"));
        scoreColumn.setCellValueFactory(new PropertyValueFactory<>("score"));

        // 使成绩列可编辑
        studentGradesTableView.setEditable(true);
        scoreColumn.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleStringConverter()));
        scoreColumn.setOnEditCommit(event -> {
            Grade grade = event.getRowValue();
            Double newScore = event.getNewValue();
            if (newScore != null && newScore >= 0 && newScore <= 100) {
                grade.setScore(newScore);
                updateGradeInDatabase(grade);
            } else {
                showAlert(Alert.AlertType.ERROR, "成绩输入错误", "请输入0-100之间的有效成绩！");
                studentGradesTableView.refresh();
            }
        });

        System.out.println("TeacherViewStudentGradesController initialized.");
    }

    @FXML
    private void handleSearchStudent() {
        String studentUsername = studentUsernameField.getText().trim();
        String studentName = studentNameField.getText().trim();
        String courseName = courseNameField.getText().trim();
        String semester = semesterField.getText().trim();

        // 如果所有查询条件都为空，则提示用户
        if (studentUsername.isEmpty() && studentName.isEmpty() && courseName.isEmpty() && semester.isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "输入错误", "请输入至少一个查询条件！");
            return;
        }

        System.out.println("Searching for grades with conditions: Username=" + studentUsername + ", Name=" + studentName + ", Course=" + courseName + ", Semester=" + semester);

        try {
            // 调用DAO方法进行多条件查询
            List<Grade> grades = gradeDAO.searchStudentGrades(studentUsername, studentName, courseName, semester);
            loadStudentGradesIntoTable(grades);
            if (grades.isEmpty()) {
                showAlert(Alert.AlertType.INFORMATION, "查询结果", "未找到匹配的成绩记录。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "数据库错误", "查询学生成绩失败：" + e.getMessage());
        }
    }

    private void loadStudentGradesIntoTable(List<Grade> grades) {
        ObservableList<Grade> observableGrades = FXCollections.observableArrayList(grades);
        studentGradesTableView.setItems(observableGrades);
        System.out.println("Loaded " + grades.size() + " student grades into table.");
    }

    private void updateGradeInDatabase(Grade grade) {
        try {
            gradeDAO.updateStudentGrade(grade);
            System.out.println("Grade updated in DB for student: " + grade.getStudentUsername() + ", course: " + grade.getCourseName() + ", semester: " + grade.getSemester() + ", new score: " + grade.getScore());
        } catch (SQLException e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "数据库错误", "更新成绩失败：" + e.getMessage());
            // 如果更新失败，可以考虑重新加载该学生的成绩以显示旧值
            // handleSearchStudent(); 
        }
    }

    private void showAlert(Alert.AlertType type, String title, String message) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 